package com.example.myyunpan.Controller;

import com.example.myyunpan.annotation.GlobalIntercepter;
import com.example.myyunpan.annotation.VerifyParam;
import com.example.myyunpan.entity.config.AppConfig;
import com.example.myyunpan.entity.constants.Constants;
import com.example.myyunpan.entity.domain.FileInfo;
import com.example.myyunpan.entity.dto.SessionWebUserDto;
import com.example.myyunpan.entity.dto.UploadResultDto;
import com.example.myyunpan.entity.enums.FileCategoryEnums;
import com.example.myyunpan.entity.enums.FileDelFlagEnums;
import com.example.myyunpan.entity.enums.FileFolderTypeEnums;
import com.example.myyunpan.entity.query.FileInfoQuery;
import com.example.myyunpan.entity.vo.FileInfoVO;
import com.example.myyunpan.entity.vo.FolderVO;
import com.example.myyunpan.entity.vo.PaginationResultVO;
import com.example.myyunpan.entity.vo.ResponseVO;
import com.example.myyunpan.service.FileInfoService;
import com.example.myyunpan.utils.MyFileUtils;
import com.example.myyunpan.utils.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileInfoController {

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    public MyFileUtils myFileUtils;

    @Autowired
    private AppConfig appConfig;

    /**
     * 根据条件分页查询
     */
    @RequestMapping("/loadDataList")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO loadDataList(HttpSession session, FileInfoQuery query,String categoryId){
        FileCategoryEnums categoryEnum = FileCategoryEnums.getByCode(categoryId);
        if(categoryEnum != null){
            query.setFileCategory(categoryEnum.getCategory());
        }
        SessionWebUserDto sessionwebuserdto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        query.setUserId(sessionwebuserdto.getUserId());
        query.setOrderBy("last_update_time desc");
        query.setDelFlag(FileDelFlagEnums.USING.getFlag());
        PaginationResultVO resultVO = fileInfoService.queryPageInfo(query);
        return ResponseVO.success(resultVO);
    }

    @RequestMapping("/uploadFile")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO uploadFile(HttpSession session,
                                 String fileId,
                                 MultipartFile file,
                                 @VerifyParam(required = true) String fileName,
                                 @VerifyParam(required = true) String filePid,
                                 @VerifyParam(required = true) String fileMd5,
                                 @VerifyParam(required = true) Integer chunkIndex,
                                 @VerifyParam(required = true) Integer chunks
                                 ){
        SessionWebUserDto sessionwebuserdto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        UploadResultDto resultDto = fileInfoService.uploadFile(sessionwebuserdto,fileId, file, fileName, filePid, fileMd5, chunkIndex, chunks);
        return ResponseVO.success(resultDto);
    }

    @RequestMapping("/getImage/{imageFolder}/{imageName}")
    public void getImage(HttpServletResponse response,
                         @PathVariable("imageFolder") String imageFolder,
                         @PathVariable("imageName") String imageName){
        if(StringTools.isEmpty(imageFolder) || StringTools.isEmpty(imageName) ||
                !StringTools.pathIsOk(imageFolder) || !StringTools.pathIsOk(imageName)){
            return;
        }
        String imageSuffix=StringTools.getFileSuffix(imageName);
        String imagePath=appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder + "/" + imageName;
        imageSuffix = imageSuffix.replace(".","");
        String contentType = "image/" + imageSuffix;
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "max-age-2592000");
        myFileUtils.readFile(response, imagePath);
    }

    @RequestMapping("/ts/getVideoInfo/{fileId}")
    public void getImage(HttpServletResponse response,
                         HttpSession session,
                         @PathVariable("fileId") String fileId){
        SessionWebUserDto sessionwebuserdto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
//        TODO 有问题 , 逻辑问题,文件id方面
        fileInfoService.getFile(response, fileId, sessionwebuserdto.getUserId());
    }

    @RequestMapping("/getFile/{fileId}")
    public void getFile(HttpServletResponse response,
                         HttpSession session,
                         @PathVariable("fileId") String fileId){
        SessionWebUserDto sessionwebuserdto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileInfoService.getFile(response, fileId, sessionwebuserdto.getUserId());
    }

    @RequestMapping("/newFoloder")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO newFoloder(HttpServletResponse response,HttpSession session,
                           @VerifyParam(required = true) String filePid,
                           @VerifyParam(required = true) String fileName){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfo fileInfo=fileInfoService.newFolder(filePid,webUserDto.getUserId(),fileName);
        return ResponseVO.success(fileInfo);
    }

    @RequestMapping("/getFolderInfo")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO getFolderInfo(HttpServletResponse response,HttpSession session,
                                 @VerifyParam(required = true) String path){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        List<FolderVO> folderInfo = fileInfoService.getFolderInfo(path, webUserDto.getUserId());
        return ResponseVO.success(folderInfo);
    }

    @RequestMapping("/rename")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO rename(HttpSession session,
                             @VerifyParam(required = true) String fileId,
                             @VerifyParam(required = true) String fileName){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfo rename = fileInfoService.rename(webUserDto.getUserId(), fileId, fileName);
        return ResponseVO.success(rename);
    }

    /**
     * 加载所有文件夹
     */
    @RequestMapping("/loadAllFolder")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO loadAllFolder(HttpSession session,
                                    @VerifyParam(required = true) String filePid,
                                    @VerifyParam(required = true) String currentFileIds
                                    ){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setUserId(webUserDto.getUserId());
        fileInfoQuery.setFilePid(filePid);
        fileInfoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());
        if(!StringTools.isEmpty(currentFileIds)){
            fileInfoQuery.setExcludeFileIdArray(currentFileIds.split(","));
        }
        fileInfoQuery.setDelFlag(FileDelFlagEnums.USING.getFlag());
        fileInfoQuery.setOrderBy("create_time desc");
        List<FileInfo> fileInfoList = fileInfoService.findListByParam(fileInfoQuery);
        return ResponseVO.success(fileInfoList);
    }

    @RequestMapping("/changeFileFolder")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO changeFileFolder(HttpSession session,
                                       @VerifyParam(required = true) String fileIds,
                                    @VerifyParam(required = true) String filePid

    ){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileInfoService.changeFileFolder(webUserDto.getUserId(), fileIds, filePid);
        return ResponseVO.success();
    }


    @RequestMapping("/createDownloadUrl/{fileId}")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO createDownloadUrl(HttpSession session,
                                       @VerifyParam(required = true) @PathVariable("fileId") String fileId

    ){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        String code = fileInfoService.createDownloadUrl(fileId, webUserDto.getUserId());
        return ResponseVO.success(code);
    }

    @RequestMapping("/download/{code}")
    @GlobalIntercepter(checkParams = true,checkLogin = false)
    public void download(HttpSession session, HttpServletRequest request,
                               HttpServletResponse response,
                                        @VerifyParam(required = true) @PathVariable("code") String code

    ){
        fileInfoService.download(request, response, code);
    }

    @RequestMapping("/delFile")
    @GlobalIntercepter(checkParams = true)
    public ResponseVO delFile(HttpSession session, @VerifyParam(required = true) String fileIds){
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileInfoService.removeFile4RecycleBatch(webUserDto.getUserId(),fileIds);
        return ResponseVO.success();
    }




}
